//每个conn绑定一个path,变动则推送
const {connect,timeout}= require('../config.json').zk
const zk = require('node-zookeeper-client').createClient(connect,{sessionTimeout:timeout*1000})
zk.connect()


//增加渠道
exports.add = async (conn,channel,callback)=>{
	if(conn.$.channel){
		let chns = conn.$.channel
		let exists = false
		for(let chn of chns){
			if(chn==channel){
				exists = true 
			}
		}
		if(!exists){
			conn.$.channel.push(channel)
			zk.getData(channel,(err,data)=>{
				if(!data){
					zk.create(channel,Buffer.from('null msg'),function(){})
				}
			});
		}
	}else{
		conn.$.channel=[channel]
	}
	callback(`添加成功 ${channel}`)
}
//列举渠道
exports.ls = async (conn,msg,callback)=>{
	let channel = conn.$.channel
	callback(`${channel}`)
}
//退出渠道
exports.quit = async (conn,channel,callback)=>{
	if(conn.$.channel){
		let chns = conn.$.channel
		let exists = false
		let index =0
		for(let i in chns){
			if(chn==channel){
				exists = true 
			}
		}
		if(!exists){
			conn.$.channel.splice(index,1)
		}
	}
	callback(`退出成功 ${channel}`)
}
//发送消息
exports.send = async (conn,msg,callback)=>{
	if(conn.$.channel){
		let chns = conn.$.channel
		let time = new Date()
		let smsg=msg+time
		for(let chn of chns){
			zk.setData(chn, Buffer.from(smsg), function (){});
		}
	}
	callback(`发送成功`)
}
//获取消息
exports.getDataHandle = async (conn)=>{
	let chns = conn.$.channel
	let emitter = conn.$.event
	for(let chn of chns){
		zk.getData(chn,(err,data)=>{
			if(data){
				let result = data.toString()
				if(conn.$.msgMap.get(chn) != result){
					conn.$.msgMap.set(chn,result)
					emitter.emit('received',chn,result)
				}
			}
			
		})
	}
}
//用户关闭连接
exports.close = async (conn,callback)=>{
	
}



// 测试
if (require.main === module) {
	// console.log(exports)
	// client.connect({connect:'127.0.0.1:2181',sessionTimeout:5000});
	// (async ()=>{
	// 	let data = await client.getData('/test')
	// 	console.log(data)
	// })();
	let zk = require('node-zookeeper-client').createClient('127.0.0.1:2181',{sessionTimeout:5000});
	zk.connect();
	zk.getData('/test',(err,data)=>{console.log(data.toString())})
	zk.exists('/test',(err,data)=>{console.log(data)})
	zk.remove('/test/aa',(err)=>{console.log(err)})
	zk.create('/test/aa',Buffer.from('按时'),(err,data)=>{console.log(data)});
	zk.setData('/test/aa', Buffer.from('按时1'), function (error, stat){});
	zk.getData('/test/aa',(err,data)=>{console.log(data.toString())})

	zk.getData('/test/aa1',(err,data)=>{console.log(err,'1111',data)})
}